package com.tongzhan.file;

import com.tongzhan.entity.FileInfo;
import com.tongzhan.repository.FileInfoRepository;
import com.tongzhan.utils.SnowFlakeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;

/**
 * 文件信息生成类
 * @Date 2020/07/24
 */
@Component
public class FileGenerate {

    private static FileGenerate fileGenerate;

    private FileInfoRepository fileInfoRepository;

    @Autowired
    private void setFileInfoRepository(FileInfoRepository fileInfoRepository) {
        this.fileInfoRepository = fileInfoRepository;
    }

    @PostConstruct
    public void init() {
        fileGenerate = this;
        fileGenerate.fileInfoRepository = this.fileInfoRepository;
    }

    public static void generate(String fileUrls, String userName) {
        if (StringUtils.isNotEmpty(fileUrls)) {
            SnowFlakeUtils snow = new SnowFlakeUtils(4, 5);
            String[] files = fileUrls.split(",");
            for (String file : files) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setForeignKey(userName);
                fileInfo.setPath(file);
                //文件名
                fileInfo.setName(file.substring(file.lastIndexOf("/") + 1));
                fileInfo.setType(file.substring(file.lastIndexOf(".") + 1));
                fileInfo.setCreateTime(LocalDateTime.now());
                fileInfo.setFileCode(String.valueOf(snow.nextId()));
                fileGenerate.fileInfoRepository.insert(fileInfo);
            }
        }
    }
}
